package com.xxgc.mq.message;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Map;
import java.util.Random;

/**
 * 手动签收
 */
@Component
public class WllxgMessageDeploy {

    @RabbitListener(queues = "my_queue")
    public void listenMessage(Message message , Channel channel) throws IOException, ClassNotFoundException {
        byte[] body = message.getBody();
        ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(body));
        Map map =(Map) objectInputStream.readObject();
        //-------业务逻辑--------
        //消息的序列号每次投递这个值都会+1
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try{
            //如果能被2整出就抛异常
            int i = new Random().nextInt(100);
            if(i % 2 == 0){
                throw new RuntimeException();
            }
            Thread.sleep(2000);
            channel.basicAck(deliveryTag,true);
            System.out.println("我已签收"+map.toString());
        }catch (Exception e){
            channel.basicNack(deliveryTag,true,true);
            System.out.println("我已拒签");
        }

    }
}
